<template>
  <div class="ueditor" :class="{
    newstyle: newstyle
    }">
    <script :id="id" name="content" type="text/plain"></script>
  </div>
</template>
<script>
  export default {
    name: 'vUeditor',
    props: {
      newstyle: {
        type: Boolean,
        default: false
      },
      content: {
        type: String,
        default: ''
      },
      config: {
        type: Object,
        default: () => {
        }
      },
      id: {
        type: String,
        required: true
      },
      useCustomUpload: { // 使用dxy 公共服务
        type: Boolean,
        default: false
      }

    },
    data() {
      return {
        instance: null
      }
    },
    watch: {
      content(val) {
        if (this.instance) {
          try {
            this.instance.setContent(val)
          } catch (e) {
            console.error(e)
          }
        }
      }
    },
    methods: {
      setContent() {
        this.instance.setContent(this.content)
      },
      init() {
        this.instance = UM.getEditor(this.id, {
          autoHeightEnabled: true,
          initialFrameWidth: '100%',
          useCustomUpload: this.useCustomUpload,
          editorVersion: '1.0.0',
          ...this.config
        })
        this.instance.ready(() => {
          this.$emit('ready', this.instance)
        })
        this.instance.addListener('contentChange', () => {
          this.$emit('change', this.instance)
        })
        this.instance.addListener('selectionchange', (editor) => {
          this.instance.fireEvent('contentChange')
        })
        this.instance.setHeight(500);

      }
    },
    mounted() {
      this.$nextTick(() => {
        this.init();
        document.getElementById('ueditor').style.maxHeight = '100%';
      })
    },
    beforeDestroy() {
      // 组件销毁的时候，要销毁 UEditor 实例
      if (this.instance !== null && this.instance.destroy) {
        this.instance.destroy()
      }
    }
  }
</script>
